<script setup lang="ts">
import { CodeInfo } from '@/assets/api/rtdatasubscriberservice_0_0_1';
import * as rtdataSubscriberService from '@/assets/api/rtdatasubscriberservice_0_0_1';
import { ElMessage } from 'element-plus';
import { onUnmounted } from 'vue';
import { onMounted } from 'vue';
import { reactive } from 'vue';


const emit = defineEmits<{
  (e: "select", CodeInfo)
}>();

const data = reactive<{
  show: boolean,
  keyword: string,
  searching: boolean,
  codeList: Array<CodeInfo>
  selectedIndex: number,
}>({
  show: false,
  keyword: "",
  searching: false,
  codeList: [],
  selectedIndex: 0,
});

const onSelect = (index: number) => {

  emit("select", data.codeList[index]);
  setTimeout(() => {
    escKeyboardElf();
  }, 200);
};

const searchCode = async () => {
  if (data.keyword.length == 0) {
    return;
  }
  if (data.searching) {
    return;
  }

  data.searching = true;

  const res = await rtdataSubscriberService.SearchCode({
    keyword: data.keyword
  });

  data.searching = false;
  if (res.err_code !== 0) {
    ElMessage.error(res.err_msg);
    return;
  }
  data.codeList = res.data.datas;
};

// 退出/隐藏键盘精灵
const escKeyboardElf = () => {
  data.keyword = "";
  data.show = false;
  data.searching = false;
  data.codeList = [];
  data.selectedIndex = 0
};
const onKeyDown = (e: KeyboardEvent) => {
  //
  if (e.ctrlKey) {
    return;
  }

  if (e.key === 'Escape') {
    // esc
    if (data.show) {
      //
      escKeyboardElf();
    }
    return;
  }

  e.preventDefault();

  if (data.searching) {
    return;
  }
  if (e.key === "Backspace") {
    data.keyword = data.keyword.slice(0, -1);
    if (data.keyword.length === 0) {
      escKeyboardElf();
    } else {
      searchCode();
    }
    return;
  }
  // 数字0-9、字母a-z,A-Z
  if (e.key.match(/^[A-Za-z0-9]$/)) {
    data.show = true;
    data.keyword += e.key;
    //搜索
    searchCode();
    return;
  }

  if (!data.show) {
    return;
  }
  if (e.key === "ArrowUp") {
    data.selectedIndex -= 1;
    if (data.selectedIndex < 0) {
      data.selectedIndex = 0;
    }
  } else if (e.key === "ArrowDown") {
    data.selectedIndex += 1;
    if (data.selectedIndex >= data.codeList.length) {
      data.selectedIndex = data.codeList.length - 1;
    }
  } else if (e.key === "Enter") {
    // 回车键
    // emit("select", data.codeList[data.selectedIndex]);

    onSelect(data.selectedIndex);
  }

};

onMounted(() => {
  document.addEventListener("keydown", onKeyDown);

});

onUnmounted(() => {
  document.removeEventListener('keydown', onKeyDown);
});


</script>

<template>
  <!-- 键盘精灵（右下角） -->
  <div class="keyboard-elf" v-show="data.show">
    <h3>
      DQT 键盘精灵 <span class="tip">按 ESC 退出</span>
    </h3>
    <el-input :model-value="data.keyword" placeholder="键盘精灵" style="width: 100%;" />


    <div class="results" id="keyboardElf-result-list">
      <p v-if="data.searching" class="tip">
        搜索中
      </p>
      <div v-else>
        <p v-if="!data.codeList.length" class="tip">无搜索结果</p>
        <el-row v-for="(item, i) in data.codeList" :key="i" :class="{ selected: i === data.selectedIndex }"
          @click="onSelect(i)" :title="item.name">
          <el-col :span="12" class="name">{{ item.name }}</el-col>
          <el-col :span="12" class="symbol">{{ item.code }}</el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
// 键盘精灵
.keyboard-elf {
  position: fixed;
  bottom: 20px;
  right: 20px;
  width: 320px;
  padding: 0 10px;
  background-color: #fff;
  z-index: 9;
  box-shadow: 1px 2px 20px 8px rgba(0, 0, 0, 0.2);
  border-radius: 5px;

  >h3 {
    line-height: initial;
    margin: 10px 0;

    >.tip {
      float: right;
      font-size: 12px;
      color: #cdcdcd;
    }
  }

  .results {
    height: 300px;
    margin: 10px 0;
    overflow-y: auto;

    .tip {
      color: #666;
      text-align: center;
      margin-top: 100px;

      // .spin {
      //   margin-right: 3px;

      //   /* 旋转图标 */
      //   @keyframes spin {
      //     from {
      //       transform: rotate(0deg);
      //     }

      //     to {
      //       transform: rotate(360deg);
      //     }
      //   }

      //   /* 旋转动画 */
      //   animation: spin 2s linear infinite;
      // }
    }

    >p {
      padding: 0 10px;
    }

    .el-row {
      height: 30px;
      line-height: 30px;
      padding: 0 10px;
      margin-right: 2px;
      border-radius: 3px;
      font-size: 12px;

      &:hover {
        background-color: #677BE1;
        color: #fff;
        cursor: pointer;
      }

      .name {
        overflow: hidden;
        width: 134px;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }

    .el-row.selected {
      background-color: #3E4FA7;
      color: #fff;
    }
  }
}
</style>